package com.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.http.fileupload.util.Streams;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 公共
 *
 * @author lzd
 */
public class Public {
	private static Log log = LogFactory.getLog(Public.class);

	/**
	 * 将集合拼接成字符串 ,隔开
	 */
	public static String listSplltString(List<Map<String, Object>> list, String key) {
		String key_value = "";
		if (list == null){
			return key_value;
		}
		String key_id = "";
		for (Map<String, Object> map : list) {
			key_id = Public.mapObjectToString(map, key);
			if (key_id != "") {
				if (key_value != "") {
					key_value += ",";
				}
				key_value += key_id;
			}
		}
		return key_value;
	}

	/**
	 * 将集合拼接成字符串 ,隔开
	 */
	public static String mapSplltString(Map<String, Object> map) {
		String key_value = "";
		String key_id = "";
		for (String key : map.keySet()) {
			key_id = mapObjectToString(map, key);
			if (key_id != "") {
				if (key_value != "") {
					key_value += ",";
				}
				key_value += key_id;
			}
		}
		return key_value;
	}

	/**
	 * 将map<string,object> 转成 string 类型
	 */
	public static String mapObjectToString(Map<String, Object> map, String key) {
		// modified by kongxm@20150625 这边有一个bug，如果map是空的话，会挂掉
		if (map == null) {
			return "";
		}

		String value = "";
		if (map.containsKey(key) && map.get(key) != null) {
			value = map.get(key).toString();
		}
		return value;
	}

	/**
	 * 将map<string,object> 转成 list 类型
	 */
	public static List<Map<String, Object>> mapObjectToList(Map<String, Object> map, String key) {
		List<Map<String, Object>> value = null;
		if (map.containsKey(key) && map.get(key) != null) {
			try {
				value = (List<Map<String, Object>>) map.get(key);
			} catch (Exception e) {
				return null;
			}
		}
		return value;
	}

	/**
	 * 将map<string,object> 转成 map<string,string> 类型
	 */
	public static Map<String, String> mapObjectToMap(Map<String, Object> map, String key) {
		Map<String, String> value = null;
		if (map.containsKey(key) && map.get(key) != null) {
			value = (Map<String, String>) map.get(key);
		}
		return value;
	}

	/**
	 * Map<String, Object> 转 Map<String, String>
	 *
	 * @param map
	 * @return
	 */
	public static Map<String, String> mapObjectToMap(Map<String, Object> map) {
		Map<String, String> value = new HashMap<String, String>(map.size());
		for (String key : map.keySet()) {
			value.put(key, mapObjectToString(map, key));
		}
		return value;
	}

	/*********************** 时间戳及时间字符串转换 ***************************/

	/**
	 * 获取当前时间时间字符串
	 */
	public static String getCurrentDay() {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date data = new Date();
		String date = df.format(data);
		return date;
	}

	/**
	 * 获取当前时间时间字符串
	 */
	public static String getCurrentDay(String format) {
		DateFormat df = new SimpleDateFormat(format);
		Date data = new Date();
		String date = df.format(data);
		return date;
	}

	/**
	 * 获取当前时间时间戳
	 */
	public static long getCurrentDayLong() {
		return System.currentTimeMillis();
	}

	/**
	 * 获取指定时间时间戳
	 *
	 * @throws ParseException
	 */
	public static long getCurrentDayLong(String time) throws ParseException {
		try {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = df.parse(time);
			return date.getTime();
		} catch (Exception e) {
			// log.error(e);
			try {
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				Date date = df.parse(time);
				return date.getTime();
			} catch (Exception e2) {
				return -1;
			}
		}
	}

	public static boolean isValidDate(String str) {
		boolean convertSuccess = true;
		// 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
		SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd");
		try {
			// 设置lenient为false.
			// 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
			format.setLenient(false);
			format.parse(str);
		} catch (ParseException e) {
			// e.printStackTrace();
			// 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
			convertSuccess = false;
		}
		return convertSuccess;
	}

	/**
	 * 获取指定时间时间戳
	 *
	 * @throws ParseException
	 */
	public static Date getCurrentDayDate(String time) throws ParseException {
		try {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = df.parse(time);
			return date;
		} catch (Exception e) {
			// log.error(e);
			try {
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				Date date = df.parse(time);
				return date;
			} catch (Exception e2) {
				return new Date();
			}
		}
	}

	// public static void main(String[] args) throws ParseException {
	// System.out.println("yyy="+mapTo("123456.123456",1.00));
	// }

	/**
	 */
	public static Date getDateForString(String pattern, String dateStr) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			return sdf.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}


	/**
	 * 10位时间戳转Date
	 * @param time
	 * @return
	 */
	public static Date TimestampToDate(Integer time){
		long temp = (long)time*1000;
		Timestamp ts = new Timestamp(temp);
		Date date = new Date();
		try {
			date = ts;
			//System.out.println(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}

	/**
	 * String(yyyy-MM-dd HH:mm:ss)转10位时间戳
	 * @param time
	 * @return
	 */
	public static Integer StringToTimestamp(String time){

		if(time.length() <= 0){
			return 0;
		}

		int times = 0;
		try {
			times = (int) ((Timestamp.valueOf(time).getTime())/1000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(times==0){
			System.out.println("String转10位时间戳失败");
		}
		return times;

	}


	/**
	 * 获得当天0点时间
	 *
	 * @return
	 */
	public static long getTimesmorning() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTimeInMillis();
	}

	/**
	 * 获得当天24点时间
	 *
	 * @return
	 */
	public static long getTimesnight() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 24);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTimeInMillis();
	}

	/**
	 * 获得当前的明天0点时间
	 *
	 * @return
	 */
	public static long getTimesOneMorning() {
		Calendar cal = Calendar.getInstance();
		// cal.set(Calendar., value)
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTimeInMillis();
	}

	/**
	 * 获得当前的明天24点时间
	 *
	 * @return
	 */
	public static long getTimesOneNight() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 24);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal.getTimeInMillis();
	}
	/**
	 * 获得昨天时间
	 *
	 * @return
	 */
	public static String getTimeYesterday(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		date = calendar.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String time =sdf.format(date);
		return time;
	}
	/**
	 * 获得前七天时间
	 *
	 * @return
	 */
	public static String getTimeSevendays(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -7);
		date = calendar.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time =sdf.format(date);
		return time;
	}

	/**
	 * 获得后七天时间
	 *
	 * @return
	 */
	public static String getAfterTimeSevendays(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, +7);
		date = calendar.getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time =sdf.format(date);
		return time;
	}

	/**
	 * 获取当前时间的顺延时间戳
	 * @param expireTime
	 * @return
	 */
	public static long getCurrTimeMillisByExpire(int expireTime){
		return System.currentTimeMillis() + expireTime * 1000L;
	}

	/**
	 * 获取上个月的时间日期 格式年-月
	 * @return
	 */
	public static String getLastMonth(){
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.MONTH, -1);
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH)+1;
		return year+"-"+String.format("%02d",month);
	}

	/**
	 * 获得年月日
	 *
	 * @param type
	 *            0：获得年月日 1：获得年 2：获得月 3：获得日 4：获得年月
	 * @return
	 */
	public static String getYearMonthDay(int type) {
		Calendar cal = Calendar.getInstance();
		if (type == 0) {
			// 查询年月日
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			return sdf.format(cal.getTime());
		} else if (type == 1) {
			// 年
			return cal.get(Calendar.YEAR) + "";
		} else if (type == 2) {
			// 月
			return (cal.get(Calendar.MONTH) + 1) + "";
		} else if (type == 3) {
			// 日
			return cal.get(Calendar.DAY_OF_MONTH) + "";
		} else if (type == 4) {
			// 年月
			if ((cal.get(Calendar.MONTH) + 1) < 10) {
				return cal.get(Calendar.YEAR) + "0" + (cal.get(Calendar.MONTH) + 1) + "";
			} else {
				return cal.get(Calendar.YEAR) + "" + (cal.get(Calendar.MONTH) + 1) + "";
			}

		}
		return "";
	}

	/***************************************** 金额转换 ******************************/
	/***
	 * 保留小数点两位
	 */
	public static String ConverToDecimalToStringTwo(Object object) {
		String _value = "0.00";
		if (object == null) {
			return _value;
		}
		String value = object.toString();
		if (StringUtils.isBlank(value)) {
			return _value;
		}
		try {
			BigDecimal bigDecimal = new BigDecimal(value);
			return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
		} catch (Exception e) {
			// log.error(e);
			return "0.00";
		}
	}

	public static float ConverToDecimalToTwo(Object object) {
		float _value = 0.00F;
		if (object == null) {
			return _value;
		}
		String value = object.toString();
		if (StringUtils.isBlank(value)) {
			return _value;
		}
		try {
			BigDecimal bigDecimal = new BigDecimal(value);
			return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		} catch (Exception e) {
			// log.error(e);
			return 0.00F;
		}
	}

	/***
	 * 保留小数点一位
	 */
	public static String ConverToDecimalToStringOne(Object object) {
		String _value = "0.0";
		if (object == null) {
			return _value;
		}
		String value = object.toString();
		if (StringUtils.isBlank(value)) {
			return _value;
		}
		try {
			BigDecimal bigDecimal = new BigDecimal(value);
			return bigDecimal.setScale(1, BigDecimal.ROUND_HALF_UP).toString();
		} catch (Exception e) {
			// log.error(e);
			return "0.0";
		}
	}

	/**
	 * 保留2位小数
	 *
	 * @param obj
	 * @return
	 */
	public static String ConverToTwoFloat(Object obj) {
		String str = obj + "";
		double num = 0;
		try {
			num = Double.parseDouble(str);
		} catch (NumberFormatException e) {
			num = 0;
			log.info("错误提示");
			e.printStackTrace();
		}
		str = String.format("%.2f", num);
		return str;
	}

	/**
	 * 保留2位小数,不会四舍五入，(例如 65.995 输出 65.99)
	 *
	 * @param obj
	 * @return
	 */
	public static double ConverToTwoFloatShe(Object obj) {
		String str = obj + "";
		double num = 0;
		try {
			num = Double.parseDouble(str);
		} catch (NumberFormatException e) {
			num = 0;
			log.info("错误提示");
			e.printStackTrace();
		}
		DecimalFormat formater = new DecimalFormat();
		formater.setMaximumFractionDigits(2);
		formater.setGroupingSize(0);
		formater.setRoundingMode(RoundingMode.FLOOR);
		return Public.mapTo(formater.format(num), 0.0);
	}

	/**
	 * 自定义保留count位小数
	 *
	 * @param obj
	 * @return
	 */
	public static String ConverToDIYFloat(Object obj, int count) {
		String str = obj + "";
		double num = 0;
		try {
			num = Double.parseDouble(str);
		} catch (NumberFormatException e) {
			num = 0;
			log.info("错误提示");
			e.printStackTrace();
		}
		if (count == 1) {
			str = String.format("%.1f", num);
		} else if (count == 2) {
			str = String.format("%.2f", num);
		} else if (count == 3) {
			str = String.format("%.3f", num);
		} else if (count >= 4) {
			str = String.format("%.4f", num);
		}
		return str;
	}

	/**
	 * 保留一位小数
	 *
	 * @param object
	 * @return
	 */
	public static float ConverToDecimalToOne(Object object) {
		float _value = 0.00F;
		if (object == null) {
			return _value;
		}
		String value = object.toString();
		if (StringUtils.isBlank(value)) {
			return _value;
		}
		try {
			BigDecimal bigDecimal = new BigDecimal(value);
			return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		} catch (Exception e) {
			// log.error(e);
			return 0.00F;
		}
	}

	/**
	 * 金额乘法
	 *
	 * @param d1
	 * @param d2
	 * @return
	 */
	public static float mul(double d1, double d2) { // 进行乘法运算
		BigDecimal b1 = new BigDecimal(d1);
		BigDecimal b2 = new BigDecimal(d2);
		return (float) b1.multiply(b2).doubleValue();
	}

	/**
	 * 金额除法
	 *
	 * @param d1
	 * @param d2
	 * @param len
	 * @return
	 */

	public static float div(double d1, double d2, int len) {// 进行除法运算
		BigDecimal b1 = new BigDecimal(d1);
		BigDecimal b2 = new BigDecimal(d2);
		return (float) b1.divide(b2, len, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

    /**
     * 金额除法 - 返回double
     * @param d1
     * @param d2
     * @param len
     * @return
     */
    public static double doubleDiv(double d1, double d2, int len) {// 进行除法运算
        BigDecimal b1 = new BigDecimal(d1);
        BigDecimal b2 = new BigDecimal(d2);
        return b1.divide(b2, len, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

	/**
	 * 提供精确加法计算的add方法
	 *
	 * @param value1
	 *            被加数
	 * @param value2
	 *            加数
	 * @return 两个参数的和
	 */
	public static float add(double value1, double value2) {
		BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
		BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
		return (float) b1.add(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); // 四舍五入.doubleValue();
	}
    /**
     * 提供精确加法计算的add方法
     *
     * @param value1
     *            被加数
     * @param value2
     *            加数
     * @return 两个参数的和
     */
    public static double doubleAdd(double value1, double value2) {
        BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
        BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
        return b1.add(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); // 四舍五入.doubleValue();
    }

	/**
	 * 提供精确减法运算的sub方法
	 *
	 * @param value1
	 *            被减数
	 * @param value2
	 *            减数
	 * @return 两个参数的差
	 */
	public static float sub(double value1, double value2) {
		BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
		BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
		double f = b1.subtract(b2).doubleValue();
		BigDecimal b = new BigDecimal(f);
		float f1 = (float) b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		return f1;

	}
	// /***************************************** IP定位
	// ******************************/
	// /**
	// * IP定位
	// *
	// * @return
	// * @throws Exception
	// */
	// public static JSONObject ipAddress(String ip) throws Exception {
	// log.info(">>>>>>>>>>> 进入通过ip获取地址方法");
	// String resultJson =
	// HttpClient.SendGET("http://api.map.baidu.com/location/ip?ak=FdqBGh4foj8BdDvsaCs3E70z&coor=bd09ll&ip="+ip,
	// null);
	// log.info(">>>>>>>>>>> 调用百度地图api结束 返回信息====" + resultJson);
	// JSONObject ob = new JSONObject();
	// try {
	// JSONObject jsonObject = JSONObject.fromObject(resultJson);
	// Map<String, Object> result = JSONUtils.toHashMap(jsonObject);
	// log.info(">>>>>>>>>>> 返回信息转换成map ==== " + result);
	// if (result != null && result.size() > 0) {
	// if(Convert.strToInt(result.get("status").toString(),0)!=0){ //内网
	// ob.put("province",IConstants.DEFAULT_PROVINCENAME);
	// ob.put("provinceId",IConstants.DEFAULT_PROVINCE);
	// ob.put("city",IConstants.DEFAULT_CITYNAME);
	// ob.put("cityId",IConstants.DEFAULT_CITY);
	// }else{
	// String type = result.get("address").toString();
	// String[] address = type.split("\\|");
	// ob.put("province", address[1]);
	// ob.put("city", address[2]);
	// JSONObject jb =
	// (JSONObject)((JSONObject)jsonObject.get("content")).get("point");
	// ob.put("coords_longitude", jb.get("x"));
	// ob.put("coords_latitude", jb.get("y"));
	// }
	//
	// }
	// } catch (Exception e) {
	// //log.error(e);
	// e.printStackTrace();
	// ob.put("msg", "百度接口错误");
	// }
	// log.info(">>>>>>>>>>> 结束通过ip获取地址方法");
	// return ob;
	//
	// }

	/**
	 * 过滤HTML标签
	 *
	 * @param inputString
	 * @return
	 */
	public static String Html2TextHtml2Text(String inputString) {
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";
		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;
		java.util.regex.Pattern p_html1;
		java.util.regex.Matcher m_html1;

		try {
			String regEx_script = "<[//s]*?script[^>]*?>[//s//S]*?<[//s]*?///[//s]*?script[//s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[//s//S]*?<///script>
			String regEx_style = "<[//s]*?style[^>]*?>[//s//S]*?<[//s]*?///[//s]*?style[//s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[//s//S]*?<///style>
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
			String regEx_html1 = "<[^>]+";
			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签

			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签

			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); // 过滤html标签

			p_html1 = Pattern.compile(regEx_html1, Pattern.CASE_INSENSITIVE);
			m_html1 = p_html1.matcher(htmlStr);
			htmlStr = m_html1.replaceAll(""); // 过滤html标签

			textStr = htmlStr;

		} catch (Exception e) {
			System.err.println("Html2Text: " + e.getMessage());
		}

		return textStr;// 返回文本字符串
	}

	/**
	 * 通过request获取请求参赛，返回map
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> requestToMap(HttpServletRequest request) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>(16);
		Map requestParams = request.getParameterMap(); // 支付宝返回的支付结果
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// e0994e42e7c1c30d94d0420f4134cb3d
			// K1ib4bQbOykKV3vTWE19azOAJnVw6bZt4v%252BwNO%252BpgHaN9w%253D%253D
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
			params.put(name, valueStr);
		}
		return params;

	}

	/************************************************
	 * 类型转换 map to
	 ******************************/

	/**
	 * Object 转 String
	 *
	 * @param value
	 * @param defaultValue
	 * @return
	 */
	public static String mapTo(Object value, String defaultValue) {
		if (value == null) {
			return defaultValue;
		}
		if (StringUtils.isBlank(value.toString())) {
			return defaultValue;
		}
		return Convert.strToStr(value.toString(), defaultValue);
	}

	/**
	 * Object 转 int
	 *
	 * @param value
	 * @param defaultValue
	 * @return
	 */
	public static int mapTo(Object value, int defaultValue) {

		if (value == null) {
			return defaultValue;
		}
		return Convert.strToInt(value.toString(), defaultValue);
	}

	/**
	 * Object 转 long
	 *
	 * @param value
	 * @param defaultValue
	 * @return
	 */
	public static long mapTo(Object value, long defaultValue) {

		if (value == null) {
			return defaultValue;
		}
		if (value instanceof Float || value instanceof Double) {
			throw new RuntimeException("类型转换错误，Object转Long");
		}
		return Convert.strToLong(value.toString(), defaultValue);
	}

	/**
	 * Object 转float
	 *
	 * @param value
	 * @param defaultValue
	 * @return
	 */
	public static float mapTo(Object value, float defaultValue) {

		if (value == null) {
			return defaultValue;
		}

		// float num=0.00f;
		// BigDecimal bigDecimal = new BigDecimal(value.toString());
		// num =(float) bigDecimal.doubleValue();

		try {
			// return num;
			// return Convert.strToFloat(value+"f", defaultValue);
			// return strToFloat(value.toString(), defaultValue);
			String va = value.toString();
			int i = va.indexOf(".");
			String integer = "0";
			String decimal = "0";
			if (i >= 0) { // 防止int型数据时报错的问题 by张磊
				integer = va.substring(0, i);
				decimal = va.substring(i + 1);
			} else {
				integer = va;
			}
			if (Float.parseFloat(decimal) < 0) {
				decimal = "0";
			}

			return Float.parseFloat(integer + "." + decimal);
		} catch (Exception e) {
			return defaultValue;
		}
	}

	/**
	 * Object 转 double
	 *
	 * @param value
	 * @param defaultValue
	 * @return
	 */
	public static double mapTo(Object value, double defaultValue) {

		if (value == null) {
			return defaultValue;
		}

		// float num=0.00f;
		// BigDecimal bigDecimal = new BigDecimal(value.toString());
		// num =(float) bigDecimal.doubleValue();

		try {
			// return num;
			// return Convert.strToFloat(value+"f", defaultValue);
			// return strToFloat(value.toString(), defaultValue);
			String va = value.toString();
			int i = va.indexOf(".");
			String integer = "0";
			String decimal = "0";
			if (i >= 0) { // 防止int型数据时报错的问题 by张磊
				integer = va.substring(0, i);
				decimal = va.substring(i + 1);
			} else {
				integer = va;
			}
			if (Double.parseDouble(decimal) < 0) {
				decimal = "0";
			}

			return Double.parseDouble(integer + "." + decimal);
		} catch (Exception e) {
			return defaultValue;
		}
	}

	public static BigDecimal mapTo(Object value, BigDecimal defaultValue) {
		try {

			BigDecimal bigDecimal = null;
			if (value instanceof BigDecimal) {
				bigDecimal = (BigDecimal) value;
			} else if (value instanceof String) {
				bigDecimal = new BigDecimal((String) value);
			} else if (value instanceof BigInteger) {
				bigDecimal = new BigDecimal((BigInteger) value);
			} else if (value instanceof Number) {
				bigDecimal = new BigDecimal(((Number) value).doubleValue());
			} else {
				return defaultValue;
			}
			return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
		} catch (Exception e) {
			return defaultValue;
		}
	}

	/**
	 * Object 转 Date
	 *
	 * @param value
	 * @param defaultValue
	 * @return
	 */
	public static Date mapTo(Object value, Date defaultValue) {

		if (value == null) {
			return defaultValue;
		}
		if (value instanceof Date || value instanceof Double) {
			throw new RuntimeException("类型转换错误，Object转Date");
		}
		return Convert.strToDate(value.toString(), defaultValue);
	}

	// public static double mapTo(Object value, double defaultValue) {
	//
	// if(value==null)
	// {
	// return defaultValue;
	// }
	// return strToDouble(value.toString(), defaultValue);
	//
	// }

	/**
	 * 计算地球上任意两点(经纬度)距离
	 *
	 * @param long1
	 *            第一点经度
	 * @param lat1
	 *            第一点纬度
	 * @param long2
	 *            第二点经度
	 * @param lat2
	 *            第二点纬度
	 * @return 返回距离 单位：米
	 */
	public static double Distance(double long1, double lat1, double long2, double lat2) {
		double a, b, R;
		R = 6378137; // 地球半径
		lat1 = lat1 * Math.PI / 180.0;
		lat2 = lat2 * Math.PI / 180.0;
		a = lat1 - lat2;
		b = (long1 - long2) * Math.PI / 180.0;
		double d;
		double sa2, sb2;
		sa2 = Math.sin(a / 2.0);
		sb2 = Math.sin(b / 2.0);
		d = 2 * R * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1) * Math.cos(lat2) * sb2 * sb2));
		return d;
	}

	/**
	 * 字符串转Double
	 *
	 * @param num
	 * @param default_num
	 * @return
	 */
	public static Double strToDouble(Object obj, double default_num) {
		if (obj == null) {
			return default_num;
		}
		String num = obj.toString();
		double return_num = default_num;
		try {
			if (StringUtils.isBlank(num)) {
				return_num = default_num;
			} else if (num.matches("^[-\\+]?[\\d]*$")) {// 如果是整数也可以
				return_num = Double.parseDouble(num);
			} else if (num.matches("^(-?\\d+)(\\.\\d+)?$")) {
				return_num = Double.parseDouble(num);
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return return_num;
	}

	/**
	 * 字符串转Float
	 *
	 * @param num
	 * @param default_num
	 * @return
	 */
	public static Float strToFloat(String obj, float default_num) {
		if (obj == null) {
			return default_num;
		}
		// ("2++111+"+obj);
		String num = obj;
		float return_num = default_num;
		// System.out.println("3+++"+num);
		try {
			if (StringUtils.isBlank(num)) {
				return_num = default_num;
			} else if (num.matches("^[-\\+]?[\\d]*$")) {// 如果是整数也可以
				return_num = Float.parseFloat(num);
			} else if (num.matches("^(-?\\d+)(\\.\\d+)?$")) {

				return_num = Float.valueOf(num);
			}
			// System.out.println("7+++"+num);
			// System.out.println("4++111+"+return_num);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		// System.out.println("5++111+"+return_num);
		return return_num;
	}

	/**
	 * // * 密码加密 // * @param password // * @return // * @throws Exception //
	 */
	// public static String password(String password) throws Exception{
	// password =
	// com.shove.security.Encrypt.encryptSES(password,IConstants.MD5_KEY);
	// return password;
	// }
	//
	// /**
	// * 密码解码
	// * @param password
	// * @return
	// * @throws Exception
	// */
	// public static String passwordApp(String password) throws Exception{
	//
	// password=Des3.decode(password);//解密
	// password =
	// com.shove.security.Encrypt.encryptSES(password,IConstants.MD5_KEY);
	// return password;
	// }

	/**
	 * 保留一位小数
	 *
	 * @param f
	 * @return
	 */
	public static float getOneScaleFloatPrice(float f) {
		BigDecimal bidBigDecimal = new BigDecimal(f);
		float r = bidBigDecimal.setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
		return r;
	}

	/**
	 * 保留两位小数
	 *
	 * @param f
	 * @return
	 */
	public static float getSecondScaleFloatPrice(float f) {
		BigDecimal bidBigDecimal = new BigDecimal(f);
		float r = bidBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		return r;
	}

	/**
	 * 保留四为小数
	 *
	 * @param f
	 * @return
	 */
	public static float getFourScaleFloatPrice(float f) {
		BigDecimal bidBigDecimal = new BigDecimal(f);
		float r = bidBigDecimal.setScale(4, BigDecimal.ROUND_HALF_UP).floatValue();
		return r;
	}

	/**
	 * 根据两点的经纬度 计算两点之间的距离
	 *
	 * @param lat1
	 *            第一个位置的纬度
	 * @param lng1
	 *            第一个位置的经度
	 * @param lat2
	 *            第二个位置的纬度
	 * @param lng2
	 *            第为个位置的经度
	 * @return
	 */
	public static double getDistance(double lat1, double lng1, double lat2, double lng2) {
		double EARTH_RADIUS = 6378.137;
		double radLat1 = lat1 * Math.PI / 180.000;
		double radLat2 = lat2 * Math.PI / 180.000;
		double a = radLat1 - radLat2;
		double b = lng1 * Math.PI / 180 - lng2 * Math.PI / 180.000;
		double s = 2.000 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2.000), 2.000)
				+ Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2.000), 2.000)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000.000) / 10000.000;
		return s;
	}

	/**
	 *
	 * @param n
	 * @return
	 */
	public static String toNumberSystem26(long n) {
		String s = "";
		while (n > 0) {
			long m = n % 26;
			if (m == 0){m = 26;}
			s = (char) (m + 64) + s;
			n = (n - m) / 26;
		}
		return s;
	}

	/**
	 * 字符串unescape解码(特别说明：此方法只适用于javascript自带的escape方法[在文本编辑器取值时用],JAVA后台用此方法解码)
	 *
	 * @param src
	 * @return
	 */
	public static String unescape(String src) {
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < src.length()) {
			pos = src.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (src.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16);
					tmp.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
					tmp.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastPos));
					lastPos = src.length();
				} else {
					tmp.append(src.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}

	/**
	 * 字符串unescape解码(特别说明：此方法只适用于javascript自带的escape方法[在文本编辑器取值时用],JAVA后台用此方法解码)
	 *
	 * @param src
	 * @return
	 */
	public static void main(String[] args) {
		System.out.println(ValidateQuery("'or 1 = 1 -- and password='"));

	}

	/**
	 * 验证是否有SQL注入字符
	 *
	 * @param src
	 * @return
	 */
	public static String ValidateQuery(String str) {
		String tt = str.toLowerCase();
		String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
				+ "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)";
		Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
		if (sqlPattern.matcher(tt).find()) {
			throw new RuntimeException("存在sql注入");
		}
		return str;
	}

	/**
	 * 校验银行卡卡号
	 *
	 * @param cardId
	 * @return
	 */
	public static boolean checkBankCard(String cardId) {
		char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
		if (bit == 'N') {
			return false;
		}
		return cardId.charAt(cardId.length() - 1) == bit;
	}

	/**
	 * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
	 *
	 * @param nonCheckCodeCardId
	 * @return
	 */
	public static char getBankCardCheckCode(String nonCheckCodeCardId) {
		if (nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
				|| !nonCheckCodeCardId.matches("\\d+")) {
			// 如果传的不是数据返回N
			return 'N';
		}
		char[] chs = nonCheckCodeCardId.trim().toCharArray();
		int luhmSum = 0;
		for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
			int k = chs[i] - '0';
			if (j % 2 == 0) {
				k *= 2;
				k = k / 10 + k % 10;
			}
			luhmSum += k;
		}
		return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
	}

	/**
	 * 获取uuid
	 *
	 * @return
	 */
	public static String getUUId() {
		String uuid = UUID.randomUUID().toString();

		return uuid = uuid.replace("-", "");
	}

	/**
	 * 判断是否为周六周日
	 *
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static boolean isWeekend(String date) throws ParseException {
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		Date bdate = format1.parse(date);
		Calendar cal = Calendar.getInstance();
		cal.setTime(bdate);
		if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
			return true;
		} else{
			return false;
		}
	}

	/**
	 * 判断时间是否在时间段内
	 *
	 * @param time
	 *            System.currentTimeMillis()
	 * @param strDateBegin
	 *            开始时间 00:00:00
	 * @param strDateEnd
	 *            结束时间 00:05:00
	 * @return
	 */
	public static boolean isInDate(long time) {
		Calendar calendar = Calendar.getInstance();
		// 处理开始时间
		String[] startTime = "08:00:00".split(":");
		calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(startTime[0]));
		calendar.set(Calendar.MINUTE, Integer.valueOf(startTime[1]));
		calendar.set(Calendar.SECOND, Integer.valueOf(startTime[2]));
		calendar.set(Calendar.MILLISECOND, 0);
		long startTimeL = calendar.getTimeInMillis();
		// 处理结束时间
		String[] endTime = "18:00:00".split(":");
		calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(endTime[0]));
		calendar.set(Calendar.MINUTE, Integer.valueOf(endTime[1]));
		calendar.set(Calendar.SECOND, Integer.valueOf(endTime[2]));
		calendar.set(Calendar.MILLISECOND, 0);
		long endTimeL = calendar.getTimeInMillis();
		return time >= startTimeL && time <= endTimeL;
	}

	/**
	 * 获取节假日列表
	 *
	 * @return
	 */
	public static String getHolidayList() {
		// http://v.juhe.cn/calendar/year?year=2018&key=f7d130be959d2bf973ff156cfe141104
		return "";
	}

	@SuppressWarnings("unused")
	public static String downloadFile(HttpServletRequest request, String urlString) throws IOException {
		URL url = new URL(urlString);
		InputStream in = url.openStream();
		// 2.在指定文件夹下创建文件。]
		// String path =
		// request.getSession().getServletContext().getRealPath("/");
		String path = "/tmp/";
		// File dir = new File(path+"execl");
		Long timeMillis = System.currentTimeMillis();
		File file = new File(path, timeMillis + ".xlsx");
		// 3.将下载保存到文件。
		FileOutputStream out = new FileOutputStream(file);
		Streams.copy(in, out, true);
		return path + "" + timeMillis + ".xlsx";
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				System.out.println("删除单个文件" + fileName + "成功！");
				return true;
			} else {
				System.out.println("删除单个文件" + fileName + "失败！");
				return false;
			}
		} else {
			System.out.println("删除单个文件失败：" + fileName + "不存在！");
			return false;
		}
	}

	/**
	 * 获取随机数
	 * @param min
	 * @param max
	 * @return
	 */
	public static double getRandom(Double max){
		Double min = 0.01;
		int scl =  2;//小数最大位数
		int pow = (int) Math.pow(10, scl);//指定小数位
		double one = Math.floor((Math.random() * (max - min) + min) * pow) / pow;
		return one;
	}


	/**
	 * 判断int类型是否为空
	 * @param value
	 * @return
	 */
	public static Boolean isNotNull(int value) {
		if(value == -1){
			return false;
		}
		return true;
	}
	/**
	 * 判断 String 类型是否为空
	 * @param value
	 * @return
	 */
	public static Boolean isNotNull(String value){
		if("".equals(value)){
			return false;
		}
		return true;
	}

	/**
	 * 判断long类型是否为空
	 * @param value
	 * @return
	 */
	public static Boolean isNotNull(Long value){
		if(value == -1L){
			return false;
		}
		return true;
	}

	//////// 获取本机信息
	/**
	 * 获取IP地址
	 * @return
	 * @throws UnknownHostException
	 */
	public static String getHostAddress() throws UnknownHostException{
		InetAddress address = InetAddress.getLocalHost();
		return address.getHostAddress();
	}
	/**
	 * 获取域名地址
	 * @return
	 * @throws UnknownHostException
	 */
	public static String getHostName() throws UnknownHostException{
		InetAddress address = InetAddress.getLocalHost();
		return address.getHostName();
	}

	/**
	 * 获取IP地址
	 *
	 * @param request
	 * @return String
	 * @Author 科帮网
	 * @Date 2017年7月31日 更新日志
	 * 2017年7月31日  科帮网 首次创建
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			return ip;
		}
		ip = request.getHeader("X-Forwarded-For");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			int index = ip.indexOf(',');
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

}
